/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package milkyway.hightech.logging;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Logger;
//import milkyway.hightech.exceptions.SystemNotAvailableException;

/**
 *
 * @author michael
 */
public class ProxyLogging implements InvocationHandler
{
    private Object obj;

    private static final Logger logger = Logger.getLogger(ProxyLogging.class.getName());
    
    public static Object newInstance(Object obj) throws IOException
    {
	return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new ProxyLogging(obj));
    }

    /**
     *
     * @param object the object which will be used by the proxy.
     * @throws IOException any exception
     */
    public ProxyLogging(Object object) throws IOException
    {
	this.obj = object;
    }

    @Override
    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
    {
	Object result = null;

	try
	{
	    result = m.invoke(obj, args);

	    String s = "Method: " + m.getName() + " - Args:";

	    for (int i = 0; i < args.length; i++)
		s += " " + args[i].getClass().getSimpleName()
			+ " " + args[i].toString() + ", ";

	    s += "- Result: " + result.getClass().getSimpleName()
		    + " " + result + "\n";

	    logger.fine(s);
	}


	catch (InvocationTargetException e)
	{
	    logger.fine(e.getCause().getMessage());
	    //throw e.getCause();
	}
		
	catch (Exception e)
	{
	    logger.fine(e.getMessage());
	}
	
	return result;
    }
}
